package com.mxdx.edu.controller;

import com.alibaba.fastjson.JSONObject;
import com.mxdx.edu.common.ApiResult;
import com.mxdx.edu.common.CommonUtils;
import com.mxdx.edu.common.log.AppLogger;
import com.mxdx.edu.enums.ErrorEnums;
import com.mxdx.edu.model.HwStudentRecord;
import com.mxdx.edu.model.StudentScore;
import com.mxdx.edu.service.IExamLibraryService;
import com.mxdx.edu.service.IHwLibraryService;
import com.mxdx.edu.service.ISemesterService;
import com.mxdx.edu.service.IStudentService;
import com.mxdx.edu.util.RedisUtil;
import com.mxdx.edu.util.ServletUtil;
import com.mxdx.edu.util.SessionUtil;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author: liujianlu
 * @Description: 去做作业
 * @Date: Created in 15:16 2018/6/28
 */
@Controller
@RequestMapping(value = "/hw")
public class HwController extends BaseController{

    private AppLogger logger = new AppLogger(HwController.class);

    @Resource
    protected SessionUtil sessionUtil;

    @Resource
    protected RedisUtil redisUtil;

    @Resource
    protected IStudentService studentService;

    @Resource
    protected ISemesterService semesterService;

    @Resource
    protected IExamLibraryService examLibraryService;

    @Resource
    protected IHwLibraryService hwLibraryService;

    /**
     *   作业首页
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/auth/hwIndex")
    public ModelAndView hwIndex(HttpServletRequest request){
        logger.entry(ServletUtil.getClientIp(request), "hwIndex");
        ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
        ModelAndView result = new ModelAndView("/h5/hwIndex");
        List<Map<String, Object>> semesteList = new ArrayList<>();
        String studentName = "";
        String headPortrait = "";
        String mood = "";
        //String semesterName = "";
        //String semesterId = "";
        try{
            Map<String,Object> userMap = getStudentMap(request);
            String studentId = CommonUtils.getStrValueFromMap(userMap,"studentId","");
            headPortrait = CommonUtils.getStrValueFromMap(userMap, "headPortrait", "");
            studentName = CommonUtils.getStrValueFromMap(userMap, "studentName", "");
            mood = CommonUtils.getStrValueFromMap(userMap, "mood", "");

            //通过学生id查询学生信息
            Map<String, Object> findStudentMap = new HashMap<>();
            findStudentMap.put("studentId", studentId);
            Map<String, Object> studentMap = studentService.findStudentMapOneByMap(findStudentMap);
            String classId = CommonUtils.getStrValueFromMap(studentMap, "classId", "");
            //课程信息
            semesteList = semesterService.findScoreListByMap(classId,studentId);

            //semesterName = CommonUtils.getStrValueFromMap(semesteList.get(0), "semesterName", "");
            //semesterId = CommonUtils.getStrValueFromMap(semesteList.get(0), "id", "");

            logger.info(ServletUtil.getClientIp(request));
        }catch (Exception e){
            super.dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
        }
        result.addObject("courseList", semesteList);
        result.addObject("studentName", studentName);
        result.addObject("headPortrait", headPortrait);
        result.addObject("mood", mood);
        //result.addObject("semesterName", semesterName);
        //result.addObject("semesterId", semesterId);

        return result;
    }

    /**
     *   作业详情
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/auth/hwDetail")
    @ResponseBody
    public ModelAndView electionDetail(HttpServletRequest request){
        logger.entry(ServletUtil.getClientIp(request), "hwDetail");

        ApiResult<Map<String, Object>> apiResult = new ApiResult<>();

        //判断是单选还是多选 返回页面  默认返回单选页面
        ModelAndView result = new ModelAndView("/h5/hwDetail");

        Map<String,Object> userMap = getStudentMap(request);
        String studentId = CommonUtils.getStrValueFromMap(userMap,"studentId","");

        String courseId = ServletUtil.getParameterStr(request, "courseId", "");
        String semesterId = ServletUtil.getParameterStr(request, "semesterId", "");
        String hwStatus = ServletUtil.getParameterStr(request, "hwStatus", "0");
        String exceedTerm = ServletUtil.getParameterStr(request, "exceedTerm", "0");
        String optionNum = ServletUtil.getParameterStr(request, "optionNum", "0");

        Map<String, Object> hwTitleMap = new HashMap<>();
        List<Map<String, Object>> hwSubjectList = new ArrayList<>();
        List<Map<String, Object>> hwMainList = new ArrayList<>();
        List<Map<String, Object>> hwOptionList = new ArrayList<>();
        List<Map<String, Object>> hwAnswerList = new ArrayList<>();
        List<Map<String, Object>> hwExplainList = new ArrayList<>();
        List<Map<String, Object>> retList = new ArrayList<>();

        int alreadyCount = 0;

        double hwScoreSum = 0;
        //用于前台记录已做未做
        String testIds = "";
        try {

            //courseId = "694942e3b96a4f5bac3a42cd77de6eff";
            hwTitleMap = hwLibraryService.findHwTitleByCourseId(courseId);

            String hwId = CommonUtils.getStrValueFromMap(hwTitleMap, "id", "");

            hwSubjectList = hwLibraryService.findHwSubjectByHwId(hwId);
            hwMainList = hwLibraryService.findHwMainByHwId(studentId,courseId,semesterId, hwId);


            StudentScore studentScore = examLibraryService.findStudentScoreByMap(studentId,courseId,semesterId);
            if("0".equals(exceedTerm) || !"0".equals(optionNum)) {
                alreadyCount = hwLibraryService.findHwStudentCountByMap(studentId,courseId,hwId,"",0);
                testIds = hwLibraryService.findHwStudentTestIdsByMap(studentId,courseId,hwId,"",0);
                if (studentScore != null){
                    hwStatus = String.valueOf(studentScore.getHwStatus());
                }
            }
            if (studentScore != null){
                hwScoreSum = studentScore.getHwScore();
            }

            List<String> testIdList = new ArrayList<>();
            for (Map<String, Object> testIdMap : hwMainList) {

                testIdList.add(CommonUtils.getStrValueFromMap(testIdMap, "test_id", ""));
            }

            hwOptionList = hwLibraryService.findHwOptionByTestId(testIdList);
            hwAnswerList = hwLibraryService.findHwAnswerByTestId(testIdList);
            hwExplainList = hwLibraryService.findHwExplainByTestId(testIdList);

            //组装小题
            for (Map<String, Object> hwMainMap : hwMainList) {
                String testId = CommonUtils.getStrValueFromMap(hwMainMap, "test_id", "");
                //获取选项
                List<Map<String, Object>> tempHwOptionList = new ArrayList<>();
                for (Map<String, Object> hwOptionMap : hwOptionList) {
                    String tempTestId = CommonUtils.getStrValueFromMap(hwOptionMap, "test_id", "");
                    if (testId.equals(tempTestId)) {
                        tempHwOptionList.add(hwOptionMap);
                    }
                }
                hwMainMap.put("hwOption", tempHwOptionList);

                //获取答案
                List<Map<String, Object>> tempHwAnswerList = new ArrayList<>();
                for (Map<String, Object> hwAnswerMap : hwAnswerList) {
                    String tempTestId = CommonUtils.getStrValueFromMap(hwAnswerMap, "test_id", "");
                    if (testId.equals(tempTestId)) {
                        tempHwAnswerList.add(hwAnswerMap);
                    }
                }
                hwMainMap.put("hwAnswer", tempHwAnswerList);

                if("1".equals(exceedTerm)){
                    hwMainMap.put("answerIds", "");
                }

                //获取详解
                Map<String, Object> tempHwExplain = new HashMap<>();
                for (Map<String, Object> hwExplainMap : hwExplainList) {
                    String tempTestId = CommonUtils.getStrValueFromMap(hwExplainMap, "test_id", "");
                    if (testId.equals(tempTestId)) {
                        tempHwExplain = hwExplainMap;
                        break;
                    }
                }
                hwMainMap.put("hwExplain", tempHwExplain);
            }

            //组装大题
            for (Map<String, Object> hwSubjectMap : hwSubjectList) {
                String hwStId = CommonUtils.getStrValueFromMap(hwSubjectMap, "id", "");
                //获取小题
                for (Map<String, Object> hwMainMap : hwMainList) {
                    String tempHwStId = CommonUtils.getStrValueFromMap(hwMainMap, "hw_st_id", "");
                    if (hwStId.equals(tempHwStId)) {
                        Map<String, Object> temp = new HashMap<>();
                        temp.putAll(hwSubjectMap);
                        temp.put("hwMain", hwMainMap);
                        retList.add(temp);
                    }
                }
            }

            logger.info(ServletUtil.getClientIp(request));
        }catch (Exception ex){
            super.dealException(ErrorEnums.SYSTEM_ERROR, ex, apiResult, logger);
        }

        result.addObject("hwTitleMap",hwTitleMap);
        result.addObject("hwSubjectList",retList);
        result.addObject("courseId", courseId);
        result.addObject("semesterId", semesterId);
        result.addObject("remainTest", hwMainList.size());
        result.addObject("imageHost", imageHost);
        result.addObject("hwStatus", hwStatus);
        result.addObject("alreadyCount",alreadyCount);
        result.addObject("surplusCount",(hwMainList.size() - alreadyCount));
        result.addObject("hwScore",hwScoreSum);
        result.addObject("exceedTerm",exceedTerm);
        result.addObject("testIds",testIds);

        return result;
    }

    /**
     *   做作业
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/auth/hwDetail/do")
    @ResponseBody
    @Transactional(readOnly = false)
    public ApiResult<String> doHw(HttpServletRequest request,
                                               HttpServletResponse response) {
        logger.entry(ServletUtil.getClientIp(request), "do");
        ApiResult<String> result = new ApiResult<>();

        String courseId = ServletUtil.getParameterStr(request, "courseId", "");
        String semesterId = ServletUtil.getParameterStr(request, "semesterId", "");
        String hwId = ServletUtil.getParameterStr(request, "hwId", "");
        String hwStId = ServletUtil.getParameterStr(request, "hwStId", "");
        String testId = ServletUtil.getParameterStr(request, "testId", "");
        String answerIds = ServletUtil.getParameterStr(request, "answerIds", "");
        String lastHw = ServletUtil.getParameterStr(request, "lastHw", "0");
        String exceedTerm = ServletUtil.getParameterStr(request, "exceedTerm", "0");
        String optionNumFlag = ServletUtil.getParameterStr(request, "optionNumFlag", "0");

        boolean wasCorrect = false;

        try {

            Map<String,Object> userMap = getStudentMap(request);
            String studentId = CommonUtils.getStrValueFromMap(userMap,"studentId","");

            if (hwLibraryService.findHwStudentCountByMap(studentId,courseId,hwId,testId,1) > 0){
                wasCorrect = true;
            }
            String tempTestId = testId;
            //如果是补考  且一个都没有作答的情况 需要将后续存在答案都置为无效
            boolean exceedTermFristNumFlag = false;
            if("1".equals(exceedTerm)){
                if( "".equals(optionNumFlag)){
                    int alreadNum = hwLibraryService.findHwStudentCountByMap(studentId,courseId,hwId,null,0) ;
                    if(alreadNum>0){
                        exceedTermFristNumFlag =  true ;
                        tempTestId = null;
                        optionNumFlag = "1";
                    }
                }
            }

            hwLibraryService.hwStudentDelete(studentId, courseId, hwId, tempTestId);

            HwStudentRecord hwStudentRecord = new HwStudentRecord();

            hwStudentRecord.setId(serialService.generateSerialNum("", 8));
            hwStudentRecord.setStudentId(studentId);
            hwStudentRecord.setCourseId(courseId);
            hwStudentRecord.setSemesterId(semesterId);
            hwStudentRecord.setHwId(hwId);
            hwStudentRecord.setHwStId(hwStId);
            hwStudentRecord.setTestId(testId);
            hwStudentRecord.setAnswerIds(answerIds);
            hwStudentRecord.setRetest(Integer.parseInt(exceedTerm));

            List<String> testIdList = new ArrayList<>();
            testIdList.add(testId);

            List<Map<String,Object>> hwAnswerList = hwLibraryService.findHwAnswerByTestId(testIdList);

            List<Integer> testAnswerIdList = new ArrayList<>();
            for (Map<String,Object> testAnswerMap : hwAnswerList){

                testAnswerIdList.add(Integer.parseInt(CommonUtils.getStrValueFromMap(testAnswerMap,"test_answer_id","")));
            }

            Integer [] testAnswerIds = new Integer[testAnswerIdList.size()];

            testAnswerIdList.toArray(testAnswerIds);

            String [] answerId = answerIds.split(",");

            Integer [] answerIdss = new Integer[answerId.length];

            for(int i=0;i<answerId.length;i++){
                answerIdss[i] = Integer.parseInt(answerId[i]);
            }

            boolean correctStatus = Arrays.equals(testAnswerIds,answerIdss);

            double hwScore = 0;
            double hwScoreSum = 0;
            //检查题干 获取题目分值
            Map<String,Object> hwScoreMap = hwLibraryService.findHwMainTestByMap(testId);
            String hwScores = CommonUtils.getStrValueFromMap(hwScoreMap,"hw_score","0");
            hwScore = Double.parseDouble(hwScores);
            //判断是否正确
            if (correctStatus){
                hwStudentRecord.setCorrectStatus(1);
                hwStudentRecord.setTestScore(hwScore);
            }else {
                hwStudentRecord.setCorrectStatus(2);
            }
            hwLibraryService.hwStudentSave(hwStudentRecord);

            //修改成绩
            StudentScore studentScore = examLibraryService.findStudentScoreByMap(studentId,courseId,semesterId);
            if (studentScore == null || studentScore.getId().length() < 1){
                StudentScore studentScore1 = new StudentScore();
                studentScore1.setId(serialService.generateSerialNum("", 8));
                studentScore1.setStudentId(studentId);
                studentScore1.setCourseId(courseId);
                studentScore1.setSemesterId(semesterId);
                studentScore1.setHwScore(hwScore);
                studentScore1.setHwStatus(1);
                studentScore1.setRetest(Integer.parseInt(exceedTerm));
                examLibraryService.studentScoreSave(studentScore1);
                hwScoreSum = hwScore;
            }else {

                //当前选择正确 库中不存在正确选择
                if (correctStatus && !wasCorrect){
                    double score = hwScore + studentScore.getHwScore();
                    if(score>100){
                        score = 100;
                    }
                    studentScore.setHwScore(score);
                }else if (correctStatus && wasCorrect){
                    double score = studentScore.getHwScore();
                    if(score>100){
                        score = 100;
                    }
                    studentScore.setHwScore(score);
                }
                //当前选择不正确 库中存在正确选择
                else if(!correctStatus && wasCorrect){
                    double score = studentScore.getHwScore() - hwScore;
                    if(score<0){
                        score = 0;
                    }
                    studentScore.setHwScore(score);
                } else if(!correctStatus && !wasCorrect){
                    double score = studentScore.getHwScore();
                    if(score<0){
                        score = 0;
                    }
                    if(score>100){
                        score = 100;
                    }
                    studentScore.setHwScore(score);
                }else {
                    double score = hwScore + studentScore.getHwScore();
                    if(score>100){
                        score = 100;
                    }
                    studentScore.setHwScore(score);
                }

                studentScore.setHwStatus(1);
                if (lastHw.equals("1") || "1".equals(exceedTerm)){
                    studentScore.setHwStatus(2);
                }
                if (studentScore.getRetest() != 1) {
                    studentScore.setRetest(Integer.parseInt(exceedTerm));
                }
                examLibraryService.studentScoreUpdate(studentScore);

                hwScoreSum = studentScore.getHwScore();
            }
            result.setInfo(String.valueOf(hwScoreSum));
            result.setResult(optionNumFlag);
        }catch (Exception e) {
            super.dealException(ErrorEnums.SYSTEM_ERROR, e, result, logger);
            result.setStatus(ErrorEnums.SYSTEM_ERROR.getCode());
            result.setMessage(ErrorEnums.SYSTEM_ERROR.getDesc());
        }

        return result;
    }

}
